
package TransportesMarroquin;

import com.mysql.jdbc.Connection;

import java.awt.event.ActionEvent; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.io.FileNotFoundException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class NuevoViajeCliente extends javax.swing.JFrame {

 boolean error = false;
 int resultado;
 static int enviarcod;
 int ncod;
 static boolean nuevo = false;
 static NuevoViajePiloto va;
    public NuevoViajeCliente() {
        initComponents();
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        cape = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cnit = new javax.swing.JTextField();
        cnom = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        cemp = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        ctel = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        cod = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel4.setText("Apellido");
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel2.setText("Nombre");
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel5.setText("Nit");
        jLabel5.setName("jLabel5"); // NOI18N

        cape.setEnabled(false);
        cape.setName("cape"); // NOI18N
        cape.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                capeKeyTyped(evt);
            }
        });

        jLabel1.setText("C L I E N T E ");
        jLabel1.setName("jLabel1"); // NOI18N

        cnit.setEnabled(false);
        cnit.setName("cnit"); // NOI18N

        cnom.setEditable(true);
        cnom.setEnabled(false);
        cnom.setName("cnom"); // NOI18N
        cnom.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                cnomKeyTyped(evt);
            }
        });

        jLabel6.setText("Empresa");
        jLabel6.setName("jLabel6"); // NOI18N

        cemp.setEnabled(false);
        cemp.setName("cemp"); // NOI18N
        cemp.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                cempKeyTyped(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/1316234747_search_b.png"))); // NOI18N
        jButton2.setText("Buscar");
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(143, 0, 0));
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Nuevo Viaje ");
        jLabel3.setName("jLabel3"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(272, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel7.setText("Codigo");
        jLabel7.setName("jLabel7"); // NOI18N

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/siguiente.png"))); // NOI18N
        jButton3.setText("Siguiente");
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        ctel.setEnabled(false);
        ctel.setName("ctel"); // NOI18N
        ctel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ctelActionPerformed(evt);
            }
        });
        ctel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ctelKeyTyped(evt);
            }
        });

        jLabel8.setText("Telefono");
        jLabel8.setName("jLabel8"); // NOI18N

        cod.setText("X");
        cod.setName("cod"); // NOI18N

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/cancelar.png"))); // NOI18N
        jButton4.setText("Cancelar");
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(188, 188, 188)
                        .addComponent(jLabel7))
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addComponent(cod)
                .addContainerGap(141, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel8)
                                    .addGap(18, 18, 18)
                                    .addComponent(ctel))
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel4)
                                        .addComponent(jLabel6)
                                        .addComponent(jLabel5))
                                    .addGap(18, 18, 18)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(cemp)
                                        .addComponent(cnit)
                                        .addComponent(cape)
                                        .addComponent(cnom, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)))
                .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton3, jButton4});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cape, cemp, cnit, cnom, ctel});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cod)
                    .addComponent(jLabel1)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cnom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cape, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(cnit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(cemp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ctel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton4)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton2, jButton3});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {cape, cemp, cnit, cnom, ctel});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
      
       AyudaCliente ac = new AyudaCliente();
       ac.setVisible(true);
       ac.setBounds(this.getSize().width,0,ac.getSize().width,this.getSize().height);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
error = false;
// despues qee verifique que los datos esten bien los guardare en nuevo cliente. 
                    
    if(nuevo){
       NuevoCliente();
                    }  
  
    if(!nuevo){
        try {
                        Insertar();
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(NuevoCabezal.class.getName()).log(Level.SEVERE, null, ex);
                    }
    }
                    
                    
                 if (!error){
                    Viaje.va.dispose(); 
                    va = new NuevoViajePiloto(enviarcod); // el codigo del camion qee voy a enviar a llantasfurgon
                    va.setVisible(true);
                    
                 }                   
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
       dispose();
            Error.Mysql("DELETE from viaje where idviaje = "+enviarcod);     
            Error.Mysql("ALTER TABLE viaje auto_increment ="+enviarcod);
            Viaje v;
            v = new Viaje("SELECT * FROM viaje");
            v.setVisible(true);
            v.setBounds(114, 107, Toolkit.getDefaultToolkit().getScreenSize().width-114, Toolkit.getDefaultToolkit().getScreenSize().height-107);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void ctelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ctelActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ctelActionPerformed

    private void cnomKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cnomKeyTyped
            char c = evt.getKeyChar();
      if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) || ((c== KeyEvent.VK_SPACE)))) {
            getToolkit().beep();
            evt.consume();
}
    }//GEN-LAST:event_cnomKeyTyped

    private void capeKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_capeKeyTyped
             char c = evt.getKeyChar();
      if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) || ((c== KeyEvent.VK_SPACE)))) {
            getToolkit().beep();
            evt.consume();
}
    }//GEN-LAST:event_capeKeyTyped

    private void cempKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cempKeyTyped
             char c = evt.getKeyChar();
      if (!(Character.isLetter(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) || ((c== KeyEvent.VK_SPACE)))) {
            getToolkit().beep();
            evt.consume();
}
    }//GEN-LAST:event_cempKeyTyped

    private void ctelKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ctelKeyTyped
           char c = evt.getKeyChar();
      if (!(Character.isDigit(c) || (c == evt.VK_BACK_SPACE) || (c == evt.VK_DELETE) || ((c== evt.VK_SPACE)))) {
            getToolkit().beep();
            evt.consume();
}
    }//GEN-LAST:event_ctelKeyTyped

    public void NuevoCliente (){
        try {
            
            
            MysqlDataSource dataSource = new MysqlDataSource();
            dataSource.setUser("root");
            dataSource.setPassword("");
            dataSource.setDatabaseName("practicasp8");
            dataSource.setServerName("localhost");
             // coneccion
            Connection conexion = (Connection) dataSource.getConnection();
            ResultSet rs;
            PreparedStatement ps = null;
            ps = (PreparedStatement) conexion.prepareStatement("insert into cliente (nombre,nit,telefono,empresa,apellido) values (?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);

         
            ps.setString(1,cnom.getText()); 


           
           ps.setString(2,cnit.getText());
           
          
            try {
                 ps.setInt(3,Integer.parseInt(ctel.getText()));
            }catch(Exception e){
                   JOptionPane.showMessageDialog(rootPane, "Dato erroneo en el Teléfono, no es un dato númerico.");
          
           } // fin del catch
           
           
             ps.setString(4,cemp.getText());
           
              ps.setString(5,cape.getText());   
       
             resultado = ps.executeUpdate();
             
             rs = ps.getGeneratedKeys();
            while (rs.next()) {
                ncod = rs.getInt(1);
                
                }
              // lleno el codigo 
                cod.setText(""+ncod);
                nuevo = false;  // ahora si ya no es un nuevo 
               conexion.close(); // cierro la conexion
               ps.close();

             }catch(SQLException e){
                  nuevo = true; // error 
            System.out.println("EXCEPCION EN Base de Datos:"+e.toString());
           } // fin del catch
    }
    public void Insertar() throws FileNotFoundException{
     
    try {
           

            MysqlDataSource dataSource = new MysqlDataSource();
            dataSource.setUser("root");
            dataSource.setPassword("");
            dataSource.setDatabaseName("practicasp8");
            dataSource.setServerName("localhost");
            ResultSet rs;
            // coneccion
            Connection conexion = (Connection) dataSource.getConnection();

            PreparedStatement ps = null;
            ps = (PreparedStatement) conexion.prepareStatement("insert into viaje (id_cliente, nombre_cliente, apellido_cliente, nit_cliente,empresa_cliente,telefono_cliente) values (?,?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
// PRIMER CAMPO 
            try{
            ps.setInt(1,Integer.parseInt(cod.getText())); 
         }catch (Exception e) {
             JOptionPane.showMessageDialog(rootPane, "Dato erroneo en el codigo del cliente no es un dato númerico.");
         }
          
 // SEGUNDO CAMPO 
            ps.setString(2,cnom.getText());
            
// TERCER CAMPO 
            ps.setString(3,cape.getText());
            
// CUARTO CAMPO 
            
            ps.setString(4,cnit.getText()); 
        
// QUINTO CAMPO 
            ps.setString(5, cemp.getText());

// SEXTO CAMPO   
       if(ctel.getText().length()>8){
                 JOptionPane.showMessageDialog(rootPane,"Dato erroneo en telefono del piloto, excede lo permitido.");
        
             }
       else {
                try{
             ps.setInt(6,Integer.parseInt(ctel.getText()));
            

         }catch(Exception e)
            {
             JOptionPane.showMessageDialog(rootPane,"Dato erroneo en telefono del piloto, no es un dato númerico.");
         }      
           
       }
         
             resultado = ps.executeUpdate();
              rs = ps.getGeneratedKeys();
            while (rs.next()) {
                enviarcod = rs.getInt(1);
                
                }


// sonido

               conexion.close(); // cierro la conexion
               ps.close();

             }catch(SQLException e){
             JOptionPane.showMessageDialog(rootPane,"Error en Programa:"+e);
         
           
            error = true;
            
           } // fin del catch
}
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NuevoViajeCliente().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public static javax.swing.JTextField cape;
    public static javax.swing.JTextField cemp;
    public static javax.swing.JTextField cnit;
    public static javax.swing.JTextField cnom;
    public static javax.swing.JLabel cod;
    public static javax.swing.JTextField ctel;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
}
